//
//  ZFHorizontalMenuView.m
//  components
//
//  Created by linzaifei on 2021/9/2.
//

#import "ZFHorizontalMenuView.h"
#import "ZFMenuCollectionLayout.h"

@interface ZFHorizontalMenuView()<UICollectionViewDelegate,UICollectionViewDataSource>
@property(nonatomic,strong)UICollectionView *collectionView;


///记录当前的高度
@property(nonatomic,assign)CGFloat currentHeight;
@end
@implementation ZFHorizontalMenuView

- (instancetype)init{
    self = [super init];
    if (self) {
        [self initZFHorizontalMenuView];
    }
    return self;
}

-(void)initZFHorizontalMenuView{
    self.backgroundColor = [UIColor whiteColor];
    _contentInset = UIEdgeInsetsMake(0,0,0,0);
    _minimumLineSpacing = 0;
    _minimumInteritemSpacing = 0;
    _isNeedAnimation = NO;
    _pageControlView = [[ZFPageControlView alloc] init];
    _pageControlView.style = ZFHorizontalMenuViewPageControlStyleAnimated;
    
    [self addSubview:self.collectionView];
    [self addSubview:self.pageControlView];
    
}
- (void)setDelegate:(id<ZFHorizontalMenuViewDelegate>)delegate{
    _delegate = delegate;
    if ([self.delegate respondsToSelector:@selector(zf_customCollectionViewCellClassForHorizontalMenuView:)] &&[self.delegate zf_customCollectionViewCellClassForHorizontalMenuView:self]) {
        Class clas = [self.delegate zf_customCollectionViewCellClassForHorizontalMenuView:self];
        [self.collectionView registerClass:clas forCellWithReuseIdentifier:NSStringFromClass(ZFMenuCollectionCell.class)];
    }else if ([self.delegate respondsToSelector:@selector(zf_customCollectionViewCellNibForHorizontalMenuView:)] &&[self.delegate zf_customCollectionViewCellNibForHorizontalMenuView:self]){
        UINib *nib = [self.delegate zf_customCollectionViewCellNibForHorizontalMenuView:self];
        [self.collectionView registerNib:nib forCellWithReuseIdentifier:NSStringFromClass(ZFMenuCollectionCell.class)];
    }
}


- (void)layoutSubviews{
    [super layoutSubviews];
    CGFloat width = CGRectGetWidth(self.frame);
    if([NSStringFromCGRect(self.collectionView.frame) isEqualToString:NSStringFromCGRect(CGRectZero)]){
        
        ZFMenuCollectionLayout *layout = (ZFMenuCollectionLayout *)self.collectionView.collectionViewLayout;
        layout.minimumLineSpacing = self.minimumLineSpacing;
        layout.minimumInteritemSpacing = self.minimumInteritemSpacing;
        
        layout.row = [self pageRows];
        layout.column = [self pageColumns];
        CGFloat item_width = (width-self.contentInset.left-self.contentInset.right-([self pageColumns]-1) * self.minimumLineSpacing) / [self pageColumns];
        CGFloat item_height = item_width + 10;
        layout.itemSize = CGSizeMake(item_width,item_height);
        
        CGFloat height = (item_height*[self pageRows])+([self pageRows]-1)*_minimumInteritemSpacing;
     
        [self.collectionView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(@(self.contentInset.top));
            make.left.equalTo(@(self.contentInset.left));
            make.right.equalTo(@(-self.contentInset.right));
            make.height.equalTo(@(height));
        }];
        [self.pageControlView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.collectionView.mas_bottom).offset(5);
            make.centerX.equalTo(self.mas_centerX);
            make.bottom.equalTo(@(-self.contentInset.bottom));
        }];
        
        self.currentHeight = height;
        
        
    }
    

}


///刷新分页控件
-(void)reloadPageControl{
    
    NSInteger count = [self collectionView:self.collectionView numberOfItemsInSection:0];
    NSInteger number = [self pageRows] *[self pageColumns];
    self.pageControlView.numberOfPages = ((count % number) ==0)? (count/number):(count/number +1);
    self.pageControlView.currentPage = 0;
}

-(void)reloadData{
    [self.collectionView reloadData];
    [self reloadPageControl];
}



#pragma mark --- 计算单页行列数
-(NSInteger )pageRows{
    if ([self.delegate respondsToSelector:@selector(zf_numOfPageRowsInHorizontalMenuView:)]) {
        return [self.delegate zf_numOfPageRowsInHorizontalMenuView:self];
    }
    return 2;
}
-(NSInteger )pageColumns{
    if ([self.delegate respondsToSelector:@selector(zf_numOfPageColumnsInHorizontalMenuView:)]) {
        return [self.delegate zf_numOfPageColumnsInHorizontalMenuView:self];
    }
    return 4;
}

#pragma mark --- getter
- (UICollectionView *)collectionView{
    if (!_collectionView) {
        ZFMenuCollectionLayout *layout = [[ZFMenuCollectionLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.alwaysBounceHorizontal = YES;
        _collectionView.pagingEnabled = YES;
        _collectionView.showsHorizontalScrollIndicator = NO;
        [_collectionView registerClass:[ZFMenuCollectionCell class] forCellWithReuseIdentifier:NSStringFromClass(ZFMenuCollectionCell.class)];
    }
    return _collectionView;
}


#pragma mark --- uicollectionview delegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if([self.dataSource respondsToSelector:@selector(zf_horizontalMenuView:)]){
        return [self.dataSource zf_horizontalMenuView:self];
    }
    return 0;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ZFMenuCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass(ZFMenuCollectionCell.class) forIndexPath:indexPath];
    if ([self.delegate respondsToSelector:@selector(zf_setCustomCell:forIndex:horizontalMenuView:)] &&
        [self.delegate respondsToSelector:@selector(zf_customCollectionViewCellClassForHorizontalMenuView:)] && [self.delegate zf_customCollectionViewCellClassForHorizontalMenuView:self]) {
        [self.delegate zf_setCustomCell:cell forIndex:indexPath.row horizontalMenuView:self];
        return cell;
    }else if ([self.delegate respondsToSelector:@selector(zf_setCustomCell:forIndex:horizontalMenuView:)] &&[self.delegate respondsToSelector:@selector(zf_customCollectionViewCellNibForHorizontalMenuView:)] && [self.delegate zf_customCollectionViewCellNibForHorizontalMenuView:self]) {
        [self.delegate zf_setCustomCell:cell forIndex:indexPath.row horizontalMenuView:self];
        return cell;
    }
    ///设置标题
    if([self.dataSource respondsToSelector:@selector(zf_horizontalMenuView:titleForItemAtIndex:)]){
        cell.titleLabel.text = [self.dataSource zf_horizontalMenuView:self titleForItemAtIndex:indexPath.row];
    }else if([self.dataSource respondsToSelector:@selector(zf_horizontalMenuView:attributeTitleForItemAtIndex:) ]){
        ////设置富文本
        cell.titleLabel.attributedText = [self.dataSource zf_horizontalMenuView:self attributeTitleForItemAtIndex:indexPath.row];
    }
    
    ////设置图片 大小可以通过间距控制
    if ([self.dataSource respondsToSelector:@selector(zf_horizontalMenuView:imageForItemAtIndex:)]) {
        UIImage *image = [self.dataSource zf_horizontalMenuView:self imageForItemAtIndex:indexPath.row];
        cell.imageView.image = image;
    }else if([self.dataSource respondsToSelector:@selector(zf_horizontalMenuView:urlForItemAtIndex:)]){
        NSURL *url = [self.dataSource zf_horizontalMenuView:self urlForItemAtIndex:indexPath.row];
        if(self.defaultImage){
            [cell.imageView sd_setImageWithURL:url placeholderImage:self.defaultImage];
        }else{
            [cell.imageView sd_setImageWithURL:url];
        }
    }
    
    if([self.delegate respondsToSelector:@selector(zf_imageSizeInHorizontalMenuView:)]){
        CGSize size = [self.delegate zf_imageSizeInHorizontalMenuView:self];
        if(!CGSizeEqualToSize(CGSizeZero, size)){
            [cell.imageView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.size.equalTo(@(size));
            }];
        }
    }
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if ([self.delegate respondsToSelector:@selector(zf_horizontalMenuView:didSelectItemAtIndexPath:) ]) {
        [self.delegate zf_horizontalMenuView:self didSelectItemAtIndexPath:indexPath.row];
    }
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    NSInteger page = scrollView.contentOffset.x / CGRectGetWidth(self.collectionView.frame);
    self.pageControlView.currentPage = page;

    if (self.isNeedAnimation) {
//        [self startAnimation];
    }
}


#pragma mark --- 折叠动画
-(void)startAnimation{
    NSInteger currentPage = self.pageControlView.currentPage;
    NSInteger numberOfPages = self.pageControlView.numberOfPages;
    ZFMenuCollectionLayout *layout = (ZFMenuCollectionLayout *)self.collectionView.collectionViewLayout;
    NSInteger row = layout.row;
    NSInteger column = layout.column;
    ///总个数
    NSInteger allcount = [self collectionView:self.collectionView numberOfItemsInSection:0];
    NSInteger lastPageCount = allcount - row*column*(numberOfPages-1);///最后一页数目
    ///判断随后一页是不是数目是不是小于当前一行数目
    if(lastPageCount>column)return; ///最后一页数目大于column
    ////当前页小于并且是最后一页
    ///计算一行高度
    CGFloat lastHeight = layout.itemSize.height+layout.sectionInset.top+layout.sectionInset.bottom;
    
    if (currentPage == numberOfPages-1) {
        [UIView animateWithDuration:0.3 animations:^{
            self.collectionView.frame = CGRectMake(0, 0, CGRectGetWidth(self.frame),lastHeight);
            self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, CGRectGetWidth(self.frame),lastHeight);
            [self layoutIfNeeded];
        }];
    }else{
        ///判断当前高度是不是一样的 不一样才进行动画 否则不需要
        if (self.currentHeight== CGRectGetHeight(self.frame))  return;   ////不需动画
        [UIView animateWithDuration:0.3 animations:^{
            self.collectionView.frame = CGRectMake(0, 0,CGRectGetWidth(self.frame),self.currentHeight);
            self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, CGRectGetWidth(self.frame),self.currentHeight);
            [self layoutIfNeeded];
        }];
    }
}


   

@end


@implementation ZFMenuCollectionCell

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        [self setZFMenuCollectionCell];
    }
    return self;
}


-(void)setZFMenuCollectionCell{

    UIView *bgView = [[UIView alloc] init];
    bgView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.contentView addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.contentView);
    }];
    

    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
    imageView.translatesAutoresizingMaskIntoConstraints = NO;
    [bgView addSubview:imageView];
    _imageView = imageView;
    
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@0);
        make.size.equalTo(@(CGSizeMake(45, 45)));
        make.centerX.equalTo(bgView.mas_centerX);
    }];
    
    
    UILabel *titleLabel = [UILabel new];
    titleLabel.textColor = [UIColor grayColor];
    titleLabel.font = [UIFont systemFontOfSize:13];
    titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [bgView addSubview:titleLabel];
    _titleLabel = titleLabel;
    
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(imageView.mas_bottom).offset(6);
        make.left.right.equalTo(@0);
        make.centerX.equalTo(bgView.mas_centerX);
        make.bottom.equalTo(@0);
    }];
    
}
@end


